package javawork;

public class section6_22 {
    // 使用巴比伦方法计算平方根
    public static double sqrt(long n) {
        // 处理特殊情况：n为0
        if (n == 0) {
            return 0.0;
        }
        
        // 初始猜测值
        double lastGuess = 1.0;
        // 计算下一个猜测值
        double nextGuess = (lastGuess + n / lastGuess) / 2;
        // 定义精度阈值
        double epsilon = 0.0001;
        
        // 循环迭代，直到两个猜测值足够接近
        while (Math.abs(nextGuess - lastGuess) > epsilon) {
            lastGuess = nextGuess;
            nextGuess = (lastGuess + n / lastGuess) / 2;
        }
        
        return nextGuess;
    }
    
    // 测试程序
    public static void main(String[] args) {
        // 测试一些示例值
        long[] testValues = {0, 1, 4, 9, 16, 25, 50, 100, 200, 300};
        
        System.out.println("数值\t近似平方根\t实际平方根");
        System.out.println("----------------------------------------");
        
        for (long num : testValues) {
            double approxSqrt = sqrt(num);
            double actualSqrt = Math.sqrt(num);
            System.out.printf("%d\t%.4f\t\t%.4f%n", num, approxSqrt, actualSqrt);
        }
    }
}
    